<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      const list = [
        {
          id: 2,
          name: "张三",
        },
        {
          id: 1,
          name: "李四",
        },
      ];

      // 数组对象排序(不使用sort)
      function sortArrayObjects(array, key) {
        // accumulator, currentValue
        return array.reduce((acc, obj) => {
          const index = acc.findIndex((item) => item[key] > obj[key]);
          if (index === -1) {
            acc.push(obj);
          } else {
            acc.splice(index, 0, obj);
          }
          return acc;
        }, []);
      }

      const sortedList = sortArrayObjects(list, "id");
      console.log(sortedList);
    </script>
  </body>
</html>
